const api = require("@/api/api").api;

export const ossUploadImgUtil = {
  // type =1
  // HOUSE(1, "pic/"),//房源
  //     SHOP_AND_USER(2, "user_pic/"),//用户
  //     BOARD(3, "board_pic/"),//留言板
  //     GOODS(4, "goods_pic/"),//商品
  //     GOODS_COMMENT(5, "goods_comment_pic/"),//商品评论
  //     USER_IM(6, "user_im/");//im消息图片

  TYPE: {
    HOUSE: 1, //房源内容图片 --新  用
    SHOP_AND_USER: 2, //用户小店
    BOARD: 3, //留言板
    GOODS: 4, //商品
    GOODS_COMMENT: 5, //商品评论
    USER_IM: 6, //im消息图片
    CONTENT: 7, // 老动态--废弃
    NOTES: 8, // 笔记
    TOPIC: 9, // 话题
    CANVAS: 13,
  },
  guid() {
    return "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".replace(/[x]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c == "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  },
  async uploadImg(data = {}, success, onProgressUpdate) {
    let dataToken = await api.base.ossGetImageToken({ type: data.type });
    dataToken = dataToken.data;
    console.log(dataToken);
    let fileType = data.filePath.substring(data.filePath.lastIndexOf("."));
    let date = new Date();
    let key =
      dataToken.dir +
      date.getFullYear() +
      (date.getMonth() + 1 < 10 ? "0" : "") +
      (date.getMonth() + 1) +
      (date.getDate() < 10 ? "0" : "") +
      date.getDate() +
      "/" +
      this.guid() +
      fileType;
    console.log(key);

    console.log("开始上传");
    console.log(dataToken.host);
    let uploadTask = uni.uploadFile({
      url: dataToken.host, // 开发者服务器的URL。
      filePath: data.filePath,
      name: "file", // 必须填file。
      formData: {
        key: key,
        policy: dataToken.policy,
        OSSAccessKeyId: dataToken.accessid,
        signature: dataToken.signature,
      },
      success: (res) => {
        console.log("上传完成", res);
        // 这个是上传完成

        if (res.statusCode == 204) {
          res.url = dataToken.domain + "/" + key;
          success(res);
        } else {
          res.url = dataToken.domain + "/" + key;
          success(res);
        }
        console.log(res);
      },
      fail: (err) => {
        console.log(err);
      },
    });
    uploadTask.onProgressUpdate((res) => {
      if (typeof onProgressUpdate == "function") {
        onProgressUpdate(res);
      }
    });
  },
};
